#include "WorldStdafx.h"
#include "AvatarManager.h"
#include "Avatar.h"
#include "Exception.h"
#include "Math/UTFString.h"


AvatarManager gAvatarManager;
AvatarManager::AvatarManager(void)
{
}

AvatarManager::~AvatarManager(void)
{
	while (!m_PoolAvatar.empty())
	{
		 IAvatar* i = m_PoolAvatar.front();
		delete i;
		m_PoolAvatar.pop_front();
	}

	for(int i = 0;i < m_OnlineAvatarMap.size(); ++i)
	{
		IAvatar* av =  *m_OnlineAvatarMap.getAtIndex(i);
	}

	m_OnlineAvatarMap.clear();

}

IAvatar * AvatarManager::createAvatar( PlayerID_t id)
{
	m_avatarMutex.Acquire();
	if (m_PoolAvatar.empty())
	{
		addPoolAvatar();
	}

	IAvatar* i = getPoolAvatar();
	i->setPlayId(id);
	m_OnlineAvatarMap.insert(id,i);//
	m_avatarMutex.Release();
	//i->setPlayId(id);

	return i;
}

void	 AvatarManager::deleteAvatar(PlayerID_t id,IAvatar * ia )
{
	m_avatarMutex.Acquire();
	if (!ia)
	{
		ia = *m_OnlineAvatarMap.find(id);
	}
	if (ia)
	{
		
		m_OnlineAvatarMap.erase(id);
		m_PoolAvatar.push_back(ia);
		
	}
	m_avatarMutex.Release();
	
}

void	AvatarManager::addPoolAvatar()
{
	IAvatar * ia = new Avatar();
	m_PoolAvatar.push_back(ia);
}

IAvatar *	AvatarManager::getPoolAvatar()
{
	//m_avatarMutex.Acquire();
	IAvatar *ia = 
	m_PoolAvatar.front();
	m_PoolAvatar.pop_front();
	//m_avatarMutex.Acquire();
	return ia;
}

void AvatarManager::init()
{
	for (int i = 0; i < MAXAVATAR ; ++i)
	{
		IAvatar * ia = new Avatar();
		m_PoolAvatar.push_back(ia);
	}
}

IAvatar * AvatarManager::isOnlineAvatar( PlayerID_t id) 
{
	IAvatar ** ia = m_OnlineAvatarMap.find(id);
	if (ia)
	{
		return *ia;
	}
	return NULL;
}